<template>
	<view>
		<!-- 头部 -->
		 <uni-nav-bar background-color="#3286ed" :statusBar="true" :fixed="true" color="#fff" 
		 title="新增回库入库" left-icon="left" right-text="提交" @clickLeft="backFn" @clickRight="btnOkFn"> </uni-nav-bar>
		
		 <u--form class="form"  labelPosition="left" labelWidth="100px" :model="form" :rules="rules" ref="form">
			 <u-form-item @click="openapplication"  label="回货申请单表" prop="returnApplyNo" borderBottom ref="item1">
			 	<u--input v-model="form.returnApplyNo" :disabled="true" disabledColor="#fff" border="none" placeholder="选择回货申请单"></u--input>
			 				<u-icon slot="right" name="arrow-right"></u-icon>
			 </u-form-item>
			 <u-form-item   label="回货入库编号" prop="returnReceiptNo" borderBottom ref="item1">
			 	<u--input v-model="form.returnReceiptNo" border="none" placeholder="回货入库编号"></u--input>
			 				<u-icon slot="right" name="arrow-right"></u-icon>
			 </u-form-item>
			 <u-form-item @click='show=2'  label="入库时间" prop="warehousingTime" borderBottom ref="item1">
			 	<u--input v-model="form.warehousingTime" border="none" placeholder="入库时间"></u--input>
				<u-datetime-picker
				@cancel="show=false" @confirm="Time"
				                :show="show==2"
				                v-model="form.warehousingTime"
				                mode="date"
				        ></u-datetime-picker>
			 				<u-icon slot="right" name="arrow-right"></u-icon>
			 </u-form-item>
			 <u-form-item   label="发起人" prop="sponsorName" borderBottom ref="item1">
			 	<u--input v-model="form.sponsorName" border="none" placeholder="发起人"></u--input>
			 				<u-icon slot="right" name="arrow-right"></u-icon>
			 </u-form-item>
			 <u-form-item   label="客户名称" prop="customerName" borderBottom ref="item1">
			 	<u--input v-model="form.customerName" border="none" placeholder="客户名称"></u--input>
			 				<u-icon slot="right" name="arrow-right"></u-icon>
			 </u-form-item>
			 <u-form-item   label="业务员" prop="salesmanName" borderBottom ref="item1">
			 	<u--input v-model="form.salesmanName" border="none" placeholder="业务员"></u--input>
			 				<u-icon slot="right" name="arrow-right"></u-icon>
			 </u-form-item>
			 <u-form-item   label="申请仓库" prop="applyWarehouseName" borderBottom ref="item1">
			 	<u--input v-model="form.applyWarehouseName" :disabled="true" disabledColor="#fff" border="none" placeholder="申请仓库"></u--input>
			 				<u-icon slot="right" name="arrow-right"></u-icon>
			 </u-form-item>
			 <u-form-item   label="入库仓库" @click="WarehouseShow=true" prop="warehousingWarehouseName" borderBottom ref="item1">
			 	<u--input v-model="form.warehousingWarehouseName" :disabled="true" disabledColor="#fff" border="none" placeholder="回货仓库"></u--input>
			 				<u-icon slot="right" name="arrow-right"></u-icon>
			 </u-form-item>
			<!-- <u-form-item   label="总价" prop="totalPrice" borderBottom ref="item1">
			 	<u--input v-model="form.totalPrice" border="none" placeholder="总价"></u--input>
			 				<u-icon slot="right" name="arrow-right"></u-icon>
			 </u-form-item> -->
			 
		 </u--form>
		 <!-- 入库机器 -->
		 <view>
			 <u-cell #title>
				 <view>待入库机器</view>
			 </u-cell>
			 <uni-table border stripe emptyText="暂无更多数据" >
			 	<!-- 表头行 -->
			 	<uni-tr>
			 		<uni-th align="center" >产品名称</uni-th>
			 		<uni-th align="center" >产品编号</uni-th>
			 		<uni-th align="center" >型号</uni-th>
			 		<uni-th align="center" >机器编号</uni-th>
			 		<uni-th align="center" >仓库名称</uni-th>
			 		<uni-th align="center" >机器状态</uni-th>
			 	</uni-tr>
			 	<!-- 表格数据行 -->
			 	<uni-tr v-for="(item,index) in stayMachineList" :key="index">
			 		<uni-td align="center">{{item.productName}}</uni-td>
			 		<uni-td align="center">{{item.productNo}}</uni-td>
			 		<uni-td align="center">{{item.model}}</uni-td>
			 		<uni-td align="center">{{item.machineNo}}</uni-td>
			 		<uni-td align="center">{{item.warehouseName}}</uni-td>
			 		<uni-td align="center">
						<view v-if="item.status=='0'">正常</view>
						<view v-if="item.status=='1'">不可用</view>
						<view v-if="item.status=='2'">使用中</view>
					</uni-td>
			 	</uni-tr>
			 </uni-table>
		 </view>
		 <!-- 扫码机器 -->
		 <view  style="margin-bottom: 20px;">
		 		<u-cell>
		 			<template #title>
		 				<view class="title">机器编码：</view>
		 			</template>
		 			<template #value>
		 				<uni-icons type="scan" @click="codeBtn" size="26"></uni-icons>
		 			</template>
		 		</u-cell>
		 		<u-cell>
		 			<template #title>
		 				<u--input customStyle="height:30px" placeholder="请输入机器编码"  v-model="machineFromData.machineNo"></u--input>
		 			</template>
		 		</u-cell>
		 		<view>
		 			<u-cell >
		 				<template #title>
		 					<u-button text="扫码" @click="searchMachine"></u-button>
		 				</template>
		 			</u-cell>
		 		</view>
		 		<uni-table border stripe emptyText="暂无更多数据" >
		 			<!-- 表头行 -->
		 			<uni-tr>
		 				<uni-th align="center">产品名称</uni-th>
		 				<uni-th align="center">产品编号</uni-th>
		 				<uni-th align="center" >型号</uni-th>
		 				<uni-th align="center">机器编号</uni-th>
		 				<uni-th align="center">仓库名称</uni-th>
		 				<uni-th align="center">状态</uni-th>
		 			</uni-tr>
		 			<!-- 表格数据行 -->
		 			<uni-tr v-for="(item,index) in form.mechineList" :key="index">
		 				<uni-td align="center">{{item.productName}}</uni-td>
		 				<uni-td align="center">{{item.productNo}}</uni-td>
		 				<uni-td align="center">{{item.model}}</uni-td>
		 				<uni-td align="center">{{item.machineNo}}</uni-td>
		 				<uni-td align="center">{{item.warehouseName}}</uni-td>
		 				<uni-td align="center">{{item.status}}</uni-td>
		 			</uni-tr>
		 			
		 		</uni-table>
		 	</view>
		<u-popup :closeable="true" :show="show==1" mode="right" overlayStyle="margin-top:44px" customStyle="margin-top:44px"
					@close="show=false" >
					<view class="box">
						<u-cell >
							<template #title>
								<view style="font-size: 14px;color: #fd9540;min-width:200px;">请选择回货申请单</view>
							</template>
						</u-cell>
						<view class="itemBox">
							<view class="title">客户名称：</view>
							<u--input customStyle="height:30px" placeholder="请输入客户名称" 
							 v-model="applyform.customerName"></u--input>
						</view>
						<!-- <u-cell >
							<template #title>
								<view style="width:20px;padding-right: 20px;"><u-button color="#5ac725" text="查询" @click="SearchOrderNo"  size="mini" ></u-button></view>
							</template>
						</u-cell> -->
						<scroll-view     scroll-y="true"   style="height: 1200rpx;"       >
							<view class="right-list" v-for="item in applyList" :key="item.id">
								<view>申请单编号:{{item.returnApplyNo}}</view>
								<view>租赁销售单编号:{{item.orderNo}}</view>
								<view>客户名称:{{item.customerName}}</view>
								<view>发起人:{{item.sponsorName}}</view>
								<view class="button"  @click="checked(item)">选择</view>
							</view>
						 </scroll-view>
					</view>
					</u-popup>
					<!-- 提示 -->
					<u-toast ref="uToast"></u-toast>
					<!-- 仓库 -->
					<u-picker :show="WarehouseShow" @confirm="WarehouseConfirm" @cancel="WarehouseShow=false" :columns="WarehouseOption" keyName="warehouseName" ></u-picker>
	<u-modal showConfirmButton showCancelButton @confirm="BtnModel" @cancel="BtnShow=false" :show="BtnShow" title="提示" content='是否确认提交'></u-modal>
	</view>
</template>

<script>
	import {getReturnApplyApi,addBackwarehouseApi,editBackwarehouseApi} from '@/api/backwarehouse.js'
	import {listWarehouse} from '@/api/warehouse.js'
	import {machineList} from '@/api/machine/machine.js'
	import {listOrder} from '@/api/order/order.js'
	export default {
		data() {
			return {
				form:{
					        returnReceiptNo:'',//	是	租赁销售回货入库单号
					        warehousingTime:'',//	是	Date	入库时间
					        sponsor:'',//	是	Long	发起人
					        sponsorName:'',//	是	string	发起人名称
					        customerId:'',//	是	Long	客户
					        customerName:'',//	是	string	客户名称
					        returnApplyId:'',//	是	Long	回货申请单id
					        returnApplyNo:'',//	是	string	回货单编号
					        salesman:'',//	是	String	业务员
					        salesmanName:'',//	是	String	业务员名称
					        applyWarehouseId:'',//	是	Long	申请入库仓库
					        applyWarehouseName:'',//	是	String	申请入库仓库名称
					        warehousingWarehouseId:'',//	是	String	入库仓库
					        totalPrice:'',//	是	String	总价
					        mechineList:[],//	是	List	回库机器列表
					        warehousingWarehouseName:''
				},
				rules:{
					returnApplyNo:{type: 'string',required: true,message: '请填写回货申请表',trigger: ['blur', 'change']},
					warehousingTime:{type: 'string',required: true,message: '请填写入库时间',trigger: ['blur', 'change']},
					sponsorName:{type: 'string',required: true,message: '请填写发起人',trigger: ['blur', 'change']},
					customerName:{type: 'string',required: true,message: '请填写客户名称',trigger: ['blur', 'change']},
					salesmanName:{type: 'string',required: true,message: '请填写业务员',trigger: ['blur', 'change']},
					warehousingWarehouseName:{type: 'string',required: true,message: '请填写入库仓库',trigger: ['blur', 'change']},
				},
				show:false,
				WarehouseShow:false,//控制回货仓库
				applyform:{
					customerName:'',
					customerId:'',
					orderStatus: '1'
					
				},
				applyList:[],
				machineFromData:{
					machineNo:'',
				},//机器
				WarehouseOption:[],//回货仓库集合
				stayMachineList:[],//待出库集合
				returnApplyProductList:[],
				BtnShow:false
			};
		},
		onLoad() {
			this.getreturnappNo()
			this.getWarehouse()
			this.form.warehousingTime=this.getNowTime()
			
		},
		methods:{
			getNowTime(){
				var date= new Date()
				// console.log(date);
				var month = date.getMonth() + 1;
				var time = date.getFullYear() + "-" + month + "-" + date.getDate();
					// console.log(time);
				return time;
				
			},
			// 打开申请单详情
			async openapplication(){
				this.show=1
				let res=await getReturnApplyApi(this.applyform)
				console.log(res);
				this.applyList=res.rows
				
			},
			// 获取仓库
			async getWarehouse(){
				const res=await listWarehouse({
					pageSize:10000,
					pageNum:1,
				})
				// console.log(res);
				this.WarehouseOption.push(res.rows)
			},
			// 选中申请单
			async checked(val){
				console.log(val);
				this.returnApplyProductList=val.productList
				this.show=false
				// this.form.returnReceiptNo=val.orderNo
				this.form.returnApplyNo=val.returnApplyNo
				this.form.sponsor=val.sponsor
				this.form.sponsorName=val.sponsorName
				this.form.customerId=val.customerId
				this.form.customerName=val.customerName
				this.form.returnApplyId=val.id
				this.form.applyWarehouseId=val.warehouseId
				this.form.applyWarehouseName=val.warehouseName
				
				// 获取订单的业务员
				listOrder({orderNo:val.orderNo}).then(response=>{
					console.log(response);
					this.form.salesman=response.rows[0].salesman
					this.form.salesmanName=response.rows[0].salesmanName
				})
				
				
				
				// 通过回货申请单的子级
				const res=await getReturnApplyApi({returnApplyNo: val.returnApplyNo,orderId:val.orderId})
				console.log(res);
			  res.rows[0].machineList.forEach((item, value) => {
				if (item.machine_id) {
				  item.machineId = item.machine_id;
				  delete item.machine_id;
				}
				if (item.machine_no) {
				  item.machineNo = item.machine_no;
				  delete item.machine_no;
				}
								
				if (item.product_id) {
				  item.productId = item.product_id;
				  delete item.product_id;
				}
				if (item.product_name) {
				  item.productName =item.product_name;
				  delete item.product_name;
				}
				if (item.product_no) {
				  item.productNo = item.product_no;
				  delete item.product_no;
				}
								
				if (item.warehouse_id) {
				  item.warehouseId = item.warehouse_id;
				  delete item.warehouse_id;
				}
				if (item.warehouse_name) {
				  item.warehouseName = item.warehouse_name;
				  delete item.warehouse_name;
				}
									 
				});
				this.stayMachineList=  res.rows[0].machineList
					 console.log(res.rows[0].machineList)

			},
			// 生成入库单编号
			getreturnappNo(){
				this.form.returnReceiptNo=this.setOrderNo()
			},
			setOrderNo(){
			      var date = new Date();
			      var year = date.getFullYear();        //年 ,从 Date 对象以四位数字返回年份
			      var month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
			      var day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
			      //修改月份格式
			      if (month >= 1 && month <= 9) {
			        month = "0" + month;
			      }
			      //修改日期格式
			      if (day >= 0 && day <= 9) {
			        day = "0" + day;
			      }
			
			      let round = Math.floor(Math.random() * (999 - 100)) + 100;
			      var currentFormatDate = `${year}${month}${day}`;
			      return "HHRK"+currentFormatDate+round;
			    },
				async Time(e){
				  
					 this.form.warehousingTime=await this.getTime(e.value)
					 console.log(this.form.warehousingTime);
					 this.show=false
				 },
				 getTime(val){
				 	var date = new Date(val);
				 	var year = date.getFullYear();        //年 ,从 Date 对象以四位数字返回年份
				 	var month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
				 	var day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
				 	//修改月份格式
				 	if (month >= 1 && month <= 9) {
				 	  month = "0" + month;
				 	}
				 	//修改日期格式
				 	if (day >= 0 && day <= 9) {
				 	  day = "0" + day;
				 	}
				 	var currentFormatDate = `${year}-${month}-${day}`;
				 	return currentFormatDate
				 },
				 backFn(){
					 uni.redirectTo({
					 	url:'/pages/backwarehouse/backwarehouse'
					 })
				 },
				
				 btnOkFn(){
					 // 表单验证
					this.$refs.form.validate().then(async(res)=>{
						console.log(res);
						if(res){
							try{
								console.log(this.form);
							this.BtnShow=true
							}catch(e){
								//TODO handle the exception
								this.$refs.uToast.show({
									type: 'error',
									message:'操作失败！',
								})
								
							}
							
						}
					}).catch((error)=>{
						console.log(error);
					})
					
				 },
				 // 弹框提示
				async BtnModel(){
					 const res1=await addBackwarehouseApi(this.form)
					 if(res1.code==200){
					 	this.$refs.uToast.show({
					 		type: 'success',
					 		message:'操作成功',
					 		complete(){
					 			uni.redirectTo({
					 				url:"/pages/backwarehouse/backwarehouse"
					 			})
					 		}
					 	})
					 }
					 this.BtnShow=false
				 },
				 // 选中仓库
				 WarehouseConfirm(e){
					 // console.log(e);
					 this.form.warehousingWarehouseName=e.value[0].warehouseName
					 this.form.warehousingWarehouseId=e.value[0].id
					 this.WarehouseShow=false
				 },
				 // 右边筛选弹框查询
				 SearchOrderNo(){
					 // this.openapplication()
				 },
				// 点击扫码按钮
				codeBtn(){
					console.log('11');
					var that =this
					uni.scanCode({
						scanType: ['qrCode'],
						success: function (res) {
							console.log(res);
							console.log(res.result);
							that.machineFromData.machineNo=res.result
							that.searchMachine()
							
						}
					})
				},
				 // 扫码入库
				async  searchMachine(){
					  const res=  await machineList(this.machineFromData)
					  console.log(res);
					  // 判断该机器是否是和子级申请单型号匹配
						let isModel=this.returnApplyProductList.some(item=>{
							console.log(item.model);
							console.log(res.rows[0].model);
						  return item.model===res.rows[0].model
						})
						console.log(isModel);
						if(!isModel){
							this.$refs.uToast.show({
								type:'error',
								message:'该机器型号与申请单型号不匹配'
							})
						}else{
							// 判断是否是待入库机器
							let isHave=this.stayMachineList.some( item=>{
									  console.log(item);
							        return item.machineNo===res.rows[0].machineNo
							      })
							console.log(isHave);
							if(isHave){
								// 判断是否重复扫码
								let isRepetition=this.form.mechineList.some(item=>{return item.machineNo===res.rows[0].machineNo})
								if(!isRepetition){
									 var machine = res.rows[0];
									 this.form.mechineList.push({
											 productName:machine.productName,
											 productNo:machine.productNo,
											 productId:machine.productId,
											 model:machine.model,
											 unit:"1",
											 machineId:machine.id,
											 machineNo:machine.machineNo,
											 warehouseId:machine.warehouseId,
											 warehouseName:machine.warehouseName,
											 remark:''
										 })
										 this.$refs.uToast.show({
											 message:'出库成功！'
										 })
								}else{
									// 是重复扫码
									this.$refs.uToast.show({
										 message:'重复扫码！！'
									})
								}
							
							}else{
								// 不是待入库
								this.$refs.uToast.show({
									 message:'此机器不属于该订单！！'
								})
							}
						}
						
					  
				 }
		}
	}
</script>

<style lang="scss" scoped>
   .form{
	   background-color: #fff;
	   padding-left: 10px;
	   padding-right: 10px;
   }
   .box{
	   min-width: 300px;
	   .itemBox{
		   padding: 10px;
		   .title{
			   padding-bottom: 10px;
		   }
	   }
	  .right-list{
		;
	  	position: relative;
	  	margin: 5px;
	  	padding: 5px;
	  	border: solid 1px #c3c3c3;
	  	font-size: 12px;
	  	.button{
	  		position: absolute;
	  		right: 10px;
	  		bottom: 10px;
			color: #ff9040;
	  	}
		}
   }
</style>
